package com.sky.service.impl;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

	private final UserMapper userMapper;

	private final WeChatProperties weChatProperties;

	private final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

	private final JwtProperties jwtProperties;

	@Override
	public UserLoginVO wxLogin(UserLoginDTO userLoginDTO) {
		log.info("微信登录:{}",userLoginDTO);
		//Map<String, Object> params = new HashMap<>();
		//params.put("appid", weChatProperties.getAppid());
		//params.put("secret", weChatProperties.getSecret());
		//params.put("js_code", userLoginDTO.getCode());
		//params.put("grant_type", "authorization_code");
		//String json = HttpUtil.get(WX_LOGIN_URL, params);
		//JSONObject jsonObject = JSON.parseObject(json);
		//String openid = jsonObject.getString("openid");
		//if (StrUtil.isBlank(openid)) {
		//	log.error("微信登录失败:{}",jsonObject.getString("errmsg"));
		//	throw new RuntimeException("微信登录失败");
		//}
		String openid = "o_q-Z5f09y0-YQYzZ_QZ0Z0Z0Z0Z";
		// 校验openId
		User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getOpenid, openid));
		if (ObjectUtil.isNull(user)) {
			// 说明是新用户 创建一个
			user = new User();
			user.setOpenid(openid);
			userMapper.insert(user);
		}

		//登录成功后，生成jwt令牌
		Map<String, Object> claims = new HashMap<>();
		claims.put(JwtClaimsConstant.USER_ID, user.getId());
		String token = JwtUtil.createJWT(
				jwtProperties.getAdminSecretKey(),
				jwtProperties.getAdminTtl(),
				claims);
		//将登录者的id放到当前线程中
		BaseContext.setCurrentId(user.getId());

		// 返回数据
		return UserLoginVO.builder()
					   .id(user.getId())
					   .openid(user.getOpenid())
					   .token(token)
					   .build();
	}

    public static interface StadnardService {
    }
}
